package main

import (
	"context"
	"fmt"
	"go_keep_learning/grpc/micro/micropb"
	"net"

	"github.com/hashicorp/consul/api"
	"google.golang.org/grpc"
)

type Server struct {
	micropb.UnimplementedGreeterServer
}

func (s *Server) SayHello(ctx context.Context, in *micropb.HelloReq) (out *micropb.HelloResp, e error) {

	return &micropb.HelloResp{Message: "helllo " + in.Name}, nil
}

func main() {

	// 把grpc服务，注册到consul上
	//初始化 consul配置
	consulConfig := api.DefaultConfig()

	//创建 consul 对象
	cli, err := api.NewClient(consulConfig)

	if err != nil {
		fmt.Println(err)
		return
	}

	//告诉consul 即将注册的服务配置的信息
	registerService := &api.AgentServiceRegistration{
		ID:      "wind chime",
		Tags:    []string{"qimi"},
		Name:    "grpc and consul",
		Address: "127.0.0.1",
		Port:    8800,
		Check: &api.AgentServiceCheck{
			CheckID:  "consul grpc test",
			TCP:      "localhost:8800",
			Timeout:  "1s",
			Interval: "5s",
		},
	}

	//注册 服务到 consul 上
	cli.Agent().ServiceRegister(registerService)

	grpcServer := grpc.NewServer()

	micropb.RegisterGreeterServer(grpcServer, new(Server))

	listener, err := net.Listen("tcp", ":8800")

	if err != nil {
		fmt.Println(err)
		return
	}

	grpcServer.Serve(listener)

}
